package com.xxja.order.auth.user.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxja.order.auth.user.mapper.UserMapper;
import com.xxja.order.auth.user.pojo.User;
import com.xxja.order.config.snowId.IdWorker;
import com.xxja.order.utils.bcryt.BCryptUtil;
import com.xxja.order.utils.exception.ExceptionCast;
import com.xxja.order.utils.exception.ExceptionCode;
import com.xxja.order.utils.jwt.JwtUtils;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private IdWorker idWorker;

    /**
     * 注册
     * @param user
     * @return
     */
    public String register(User user) {
        // 实体类数据已校验过，此处不再校验
        checkName(user.getId(), user.getName());
        String encodePassword = BCryptUtil.encode(user.getPassword());
        user.setId(idWorker.nextId());
        user.setPassword(encodePassword);
        user.setCreatetime(new Date());
        user.setUpdatetime(new Date());
        Boolean result = userMapper.insert(user) == 1;
        if (result) {
            String token = JwtUtils.geneJsonWebToken(user);
            return token;
        } else {
            return "没增加进去前端看着处理";
        }
    }

    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    @Transactional
    public String query(String username, String password) {
        if (StringUtils.isEmpty(username)) {
            ExceptionCast.cast(ExceptionCode.USER_USERNAME_NONE);
        }
        if (StringUtils.isEmpty(password)) {
            ExceptionCast.cast(ExceptionCode.USER_PASSWORD_NONE);
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("name", username);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            ExceptionCast.cast(ExceptionCode.USER_NOTPASSWORD_NOTUSERNAME);
        }
        String token = JwtUtils.geneJsonWebToken(user);
        return token;

    }

    /**
     * 校验姓名是否已经存在
     * @param id
     * @param username
     */
    private void checkName(Long id, String username) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("name", username);
        if (id != null) {
            queryWrapper.notIn("id", id);
        }
        Integer integer = userMapper.selectCount(queryWrapper);
        if (integer > 0) {
            ExceptionCast.cast(ExceptionCode.USER_USERNAME_EXIST);
        }
    }
}
